Page({
  data: {
    currentGroup: 0,
    currentWordIndex: 0,
    answer: '',
    letters: ['D', 'E', 'S', 'K'],
    currentWord: {
      english: 'DESK',
      chinese: '课桌'
    },
    wordGroups: [
      {
        groupName: '学校用品',
        words: [
          { english: 'BOOK', chinese: '书', completed: false },
          { english: 'DESK', chinese: '课桌', completed: false },
          { english: 'PEN', chinese: '钢笔', completed: false },
          { english: 'BAG', chinese: '书包', completed: false },
          { english: 'CHAIR', chinese: '椅子', completed: false }
        ]
      }
    ],
    isShaking: false,
    showReward: false,
    dictType: 'course',
    grade3Expanded: false,
    grade4Expanded: false,
    starterExpanded: false,
    level1Expanded: false,
    courseDict: {
      grade3: {
        name: '三年级',
        progress: 0,
        lessons: Array(8).fill().map((_, i) => ({
          id: i + 1,
          name: `第${i + 1}课`,
          completed: false
        }))
      },
      grade4: {
        name: '四年级',
        progress: 0,
        lessons: Array(8).fill().map((_, i) => ({
          id: i + 1,
          name: `第${i + 1}课`,
          completed: false
        }))
      }
    },
    cambridgeDict: {
      starter: {
        name: '预备级',
        progress: 0,
        semesters: {
          1: Array(16).fill().map((_, i) => ({
            id: i + 1,
            name: `第${i + 1}单元`,
            completed: false
          })),
          2: Array(16).fill().map((_, i) => ({
            id: i + 1,
            name: `第${i + 1}单元`,
            completed: false
          }))
        }
      }
    }
  },

  onLoad() {
    const firstWord = this.data.wordGroups[0].words[0];
    const letters = this.generateLetters(firstWord.english);
    this.setData({
      currentWord: firstWord,
      letters: letters
    });
  },

  // 初始化当前单词
  initWord() {
    const word = this.data.wordGroups[this.data.currentGroup].words[this.data.currentWordIndex];
    const letters = this.generateLetters(word.english);
    this.setData({
      currentWord: word,
      letters: letters,
      answer: ''
    });
  },

  // 生成字母选择区的字母
  generateLetters(word) {
    let letters = word.split('');
    // 添加一些干扰字母
    const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    while (letters.length < 8) {
      const randomLetter = alphabet[Math.floor(Math.random() * alphabet.length)];
      if (!letters.includes(randomLetter)) {
        letters.push(randomLetter);
      }
    }
    // 打乱字母顺序
    return this.shuffleArray(letters);
  },

  // 打乱数组顺序
  shuffleArray(array) {
    for (let i = array.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [array[i], array[j]] = [array[j], array[i]];
    }
    return array;
  },

  // 播放单词音频
  playWord() {
    const audioContext = wx.createInnerAudioContext();
    audioContext.src = `https://dict.youdao.com/dictvoice?audio=${this.data.currentWord.english}&type=1`;
    audioContext.play();
  },

  // 选择字母
  selectLetter(e) {
    const letter = e.currentTarget.dataset.letter;
    if (this.data.answer.length < this.data.currentWord.english.length) {
      this.playSound('click');  // 添加点击音效
      const newAnswer = this.data.answer + letter;
      this.setData({
        answer: newAnswer
      });

      // 如果填满了所有字母，自动检查答案
      if (newAnswer.length === this.data.currentWord.english.length) {
        this.checkAnswer(newAnswer);
      }
    }
  },

  // 播放音效
  playSound(type) {
    const audio = wx.createInnerAudioContext();
    switch (type) {
      case 'correct':
        audio.src = '/audio/correct.mp3'
        break
      case 'wrong':
        audio.src = '/audio/wrong.mp3'
        break
      case 'click':
        audio.src = '/audio/select03 (1).mp3'
        break
    }
    audio.play()
    audio.onEnded(() => {
      audio.destroy()
    })
  },

  // 清空答案
  clearAnswer() {
    this.setData({
      answer: ''
    });
  },

  // 检查答案
  checkAnswer(answer) {
    if (answer === this.data.currentWord.english) {
      this.playSound('correct')
      // 标记当前单词为已完成
      const wordGroups = this.data.wordGroups;
      wordGroups[this.data.currentGroup].words[this.data.currentWordIndex].completed = true;

      this.setData({
        wordGroups,
        showReward: true  // 显示奖励动画
      });

      // 播放奖励动画
      setTimeout(() => {
        this.setData({ showReward: false });
      }, 1000);

      // 延迟后进入下一个单词
      setTimeout(() => {
        this.nextWord();
      }, 1500);
    } else {
      this.playSound('wrong')
      this.setData({ isShaking: true })

      setTimeout(() => {
        this.setData({ isShaking: false })
      }, 500)

      setTimeout(() => {
        this.clearAnswer();
      }, 800);
    }
  },

  // 下一个单词
  nextWord() {
    let { currentGroup, currentWordIndex } = this.data;
    const groupWords = this.data.wordGroups[currentGroup].words;

    if (currentWordIndex < groupWords.length - 1) {
      currentWordIndex++;
    } else if (currentGroup < this.data.wordGroups.length - 1) {
      currentGroup++;
      currentWordIndex = 0;
    } else {
      wx.showToast({
        title: '已完成所有单词！',
        icon: 'success'
      });
      return;
    }

    this.setData({
      currentGroup,
      currentWordIndex
    }, () => {
      this.initWord();
    });
  },

  // 下一组
  nextGroup() {
    if (this.data.currentGroup < this.data.wordGroups.length - 1) {
      this.setData({
        currentGroup: this.data.currentGroup + 1,
        currentWordIndex: 0
      }, () => {
        this.initWord();
      });
    } else {
      wx.showToast({
        title: '已是最后一组',
        icon: 'none'
      });
    }
  },

  // 切换词库类型
  switchDictType(e) {
    const type = e.currentTarget.dataset.type;
    this.setData({ dictType: type });
  },

  // 切换年级/级别的展开状态
  toggleGrade(e) {
    const grade = e.currentTarget.dataset.grade;
    const expandKey = `${grade}Expanded`;
    this.setData({
      [expandKey]: !this.data[expandKey]
    });
  },

  // 选择课程
  selectLesson(e) {
    const { grade, lesson } = e.currentTarget.dataset;
    // 加载对应课程的单词数据
    this.loadLessonWords(grade, lesson);
  },

  // 选择单元
  selectUnit(e) {
    const { level, semester, unit } = e.currentTarget.dataset;
    // 加载对应单元的单词数据
    this.loadUnitWords(level, semester, unit);
  },

  // 加载课程词库的单词数据
  loadLessonWords(grade, lesson) {
    wx.showLoading({
      title: '加载中...'
    });

    // 模拟加载数据
    setTimeout(() => {
      wx.hideLoading();
      // 这里应该是实际的数据加载逻辑
      this.setData({
        currentGroup: 0,
        currentWordIndex: 0,
        // 加载新的单词组数据
        wordGroups: []  // 这里需要设置实际的单词数据
      });
    }, 500);
  },

  // 加载剑桥词库的单词数据
  loadUnitWords(level, semester, unit) {
    wx.showLoading({
      title: '加载中...'
    });

    // 模拟加载数据
    setTimeout(() => {
      wx.hideLoading();
      // 这里应该是实际的数据加载逻辑
      this.setData({
        currentGroup: 0,
        currentWordIndex: 0,
        // 加载新的单词组数据
        wordGroups: []  // 这里需要设置实际的单词数据
      });
    }, 500);
  }
}); 